package com.csdig.cms.directive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csdig.cms.model.Channel;
import com.csdig.cms.service.ChannelService;
import com.csdig.cms.utils.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 栏目列表标签
 */
@Service("channelListDirective")
public class ChannelListDirective implements TemplateDirectiveModel {

	@Autowired
	private ChannelService channelService;

	/**
	 * 输入参数，父栏目ID。存在时，获取该栏目的子栏目，不存在时获取顶级栏目。
	 */
	public static final String PARAM_PARENT_ID = "parentId";

	public static final String PARAM_IS_DISPLAY = "isDisplay";

	public static final String SHOW_CHILDREN = "showChild";

	@SuppressWarnings("unchecked")
	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Integer parentId = DirectiveUtils.getInt(PARAM_PARENT_ID, params);
		Boolean isDisplay = DirectiveUtils.getBool(PARAM_IS_DISPLAY, params);
		Boolean showChild = DirectiveUtils.getBool(SHOW_CHILDREN, params);

		isDisplay = ((isDisplay == null) ? Boolean.TRUE : isDisplay);
		parentId = (parentId == null) ? Integer.valueOf(-1) : parentId;
		showChild = (showChild == null) ? Boolean.FALSE : showChild;

		List<Channel> list = new ArrayList<Channel>();
		// 查询
		list = channelService.getChildListForTag(parentId, isDisplay,showChild);

		//

		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(DirectiveUtils.OUT_LIST, ObjectWrapper.DEFAULT_WRAPPER.wrap(list));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}
}
